package com.example.comic.adpter

import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.comic.R
import com.example.comic.mvp.model.Book
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_book.view.*

class BookAdapter(var data: List<Book> = ArrayList(), var itemClick: (View, Int) -> Unit) : RecyclerView.Adapter<BookAdapter.BookViewHolder>() {

    companion object {
        const val TYPE_TITLE: Int = 0
        const val TYPE_CONTENT: Int = 1
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookViewHolder {
        var itemView: View = LayoutInflater.from(parent.context).inflate(R.layout.item_book, parent, false)
        return BookViewHolder(itemView)
    }

    override fun getItemCount(): Int = data.size
    override fun getItemViewType(position: Int): Int {
        if (data[position].type == 0)
            return TYPE_TITLE
        else if (data[position].type == 1)
            return TYPE_CONTENT
        return super.getItemViewType(position)
    }

    override fun onBindViewHolder(holder: BookViewHolder, position: Int) {
        bindView(holder.itemView, position)
    }

    private fun bindView(itemView: View, position: Int) {
        if (getItemViewType(position) == TYPE_CONTENT) {
            val book = data[position]
            itemView.tvTitle.text = book.title
            if (book.category.isEmpty()) {
                itemView.tvCategory.visibility = View.GONE
            } else {
                itemView.tvCategory.text = book.category
            }
            val params = itemView.layoutParams;
            Picasso.get().load(book.cover).into(itemView.ivCover)
            itemView.container.setOnClickListener { itemClick(itemView, position) }
        } else if (getItemViewType(position) == TYPE_TITLE) {
            var layoutParams = StaggeredGridLayoutManager.LayoutParams(StaggeredGridLayoutManager.LayoutParams.MATCH_PARENT,
                    StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT)
            layoutParams.isFullSpan = true
            itemView.layoutParams = layoutParams
            val book = data[position]
            itemView.tvTitle.text = book.title
            itemView.ivCover.visibility = View.GONE
            itemView.tvCategory.visibility = View.GONE
            itemView.ivIconLeft.visibility = View.VISIBLE
            itemView.ivIconRight.visibility = View.VISIBLE
            if (!book.cover.isEmpty()) {
                Picasso.get().load(book.cover).into(itemView.ivIconLeft)
                Picasso.get().load(book.cover).into(itemView.ivIconRight)
            }

        }
    }

    fun refreshData(newData: List<Book>) {
        data = newData
        notifyDataSetChanged()
    }

    class BookViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}